package com.ly.mpayment.rest.system;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import com.alibaba.fastjson.JSON;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.*;
import com.ly.mpayment.persist.service.bill.BillOrderService;
import com.ly.mpayment.persist.service.downshopproduct.IDownShopProductService;
import com.ly.mpayment.persist.service.manualorder.IManualOrderService;
import com.ly.mpayment.persist.service.mobile.IMobileService;
import com.ly.mpayment.rest.recharge.AutoOrderService;
import com.ly.mpayment.rest.recharge.OrderThread;
import com.ly.mpayment.rest.system.entity.ManualRechargeOrder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ly.mpayment.persist.service.downorderlog.IDownOrderLogService;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.persist.service.user.IUserService;
import com.ly.mpayment.rest.AbsRest;
import com.ly.mpayment.rest.recharge.OrderProcessing;
import com.ly.mpayment.rest.recharge.RechargeRest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
@Path("system/downrechargeflow/")
public class DownRechargeFlowRest extends AbsRest{
	Logger logger = Logger.getLogger(DownRechargeFlowRest.class);
	@Autowired
	IUserService userService;

	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	IUporderService orderService;

	@Autowired
	IUpShopInfoService upShopInfoService;

	@Autowired
	IDownShopInfoService shopService;

	@Autowired
	private OrderProcessing orderProcessing;

	@Autowired
	IUporderService upOrderService;

	@Autowired
	IDownOrderLogService logDownService;

	@Autowired
	RechargeRest rest;

	@Autowired
	IManualOrderService iManualOrderService;

	@Autowired
	BillOrderService billOrderService;

	@POST
	@Path("findDownOrder")
	public String findDownOrder(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data,request, userService, "start","pageSize","useruuid","busuuid","provinceuuid","downreqid","phoneNum","downorderuuid","status","createtime","endtime","operatoruid","callstatus","downfacevalue");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject jsonToken = JsonUtils.converToJson(jwt.getSubject());

						User login = userService.findByUserid(jsonToken.getString(Config.tokenSignAttr));
						if(login != null) {
							//检查是
							if (UserUtil.checkRoleDown(login)) {

								//检查日期不能大于一个月
								if(StringUtils.isBlank(json.getString("createtime"))){
									return ResultMessage.getFailt("开始日期必填");
								}
								//检查日期不能大于一个月
								if(StringUtils.isBlank(json.getString("endtime"))){
									return ResultMessage.getFailt("结束日期必填");
								}

								if(!DateUtils.parseYearDay(json.getString("createtime")).equals(DateUtils.parseYearDay(json.getString("endtime")))){
									return ResultMessage.getFailt("日期不能跨月");
								}
							}
						}

						if (jsonToken != null) {
							return ResultMessage.getSucceed(JsonUtils.excludes(this.flowService.findPageDownrechargeflow(getMap(jsonToken, parameters, json), json.getInt("start"), json.getInt("pageSize")),
									new String[]{"downOrderRefunds","downOrderLogs","upOrders","orderMatchDetails","provincialInformation","operators","user",
											"operatorsType","errorCodesForUseruuid","flowInformation","lastlogintime","password","phonenum","token","userstatus","useruuid",
											"usertype","wechatid","","","",""}));
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return result;
	}


	@SuppressWarnings("unchecked")
	@POST
	@Path("exportdataFlowOrder")
	public String exportdataFlowOrder(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data,request, userService, "useruuid","busuuid","provinceuuid","downreqid","phoneNum","downorderuuid","status","createtime","endtime","operatoruid","callstatus","downfacevalue");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject jsonToken = JsonUtils.converToJson(jwt.getSubject());
						if (jsonToken != null) {

							User login = userService.findByUserid(jsonToken.getString(Config.tokenSignAttr));
							//如果是下游客户 只能导出一个月的
							if(login != null && UserUtil.checkRoleDown(login)){
//								if(StringUtils.isBlank(json.getString("createtime"))){
//									return ResultMessage.getFailt("时间不能为空");
//								}
//								Date start = DateUtils.parseDate(json.getString("createtime"));
//								start = DateUtils.addDays(30,start);
//								if(start.compareTo(DateUtils.parseDate(json.getString("endtime"))) == -1){
//									return ResultMessage.getFailt("时间不能超过一个月");
//								}
								if(StringUtils.isBlank(json.getString("createtime"))){
									return ResultMessage.getFailt("开始日期必填");
								}
								//检查日期不能大于一个月
								if(StringUtils.isBlank(json.getString("endtime"))){
									return ResultMessage.getFailt("结束日期必填");
								}

								if(!DateUtils.parseYearDay(json.getString("createtime")).equals(DateUtils.parseYearDay(json.getString("endtime")))){
									return ResultMessage.getFailt("日期不能跨月");
								}
							}

							JSONObject obj = JsonUtils.getJSONOBJCT();
							String exportResult = ExportExcelUtil.exportDownFlow(flowService,getMap(jsonToken,parameters,json),billOrderService);
							logger.info("exportResult:"+exportResult);
							if(exportResult != null){
								obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
								return ResultMessage.getSucceed(obj.toString());
							}else{
								return ResultMessage.getFailt("");
							}
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	private Map<String, Object> getMap(JSONObject jsonToken ,Map<String, Object> parameters,JSONObject json ){
		User login = userService.findByUserid(jsonToken.getString(Config.tokenSignAttr));
		if(UserUtil.checkRoleDown(login)){
				parameters.put(":useruuid", login.getUseruuid());
		}else{
			if(!StringUtils.isBlank(json.getString("useruuid"))){
				parameters.put(":useruuid", json.getString("useruuid"));
			}
		}
		if(!StringUtils.isBlank(json.getString("operatoruid"))){
			parameters.put(":operatoruid", json.getString("operatoruid"));
		}

		if(!StringUtils.isBlank(json.getString("createtime"))){
			parameters.put(":createtime", json.getString("createtime"));
		}

		if(!StringUtils.isBlank(json.getString("endtime"))){
			parameters.put(":endtime", json.getString("endtime"));
		}

		if(!StringUtils.isBlank(json.getString("busuuid"))){
			parameters.put(":busuuid", json.getString("busuuid"));
		}
		if(!StringUtils.isBlank(json.getString("provinceuuid"))){
			parameters.put(":provinceuuid", json.getString("provinceuuid"));
		}
		if(!StringUtils.isBlank(json.getString("downreqid"))){
			parameters.put(":downreqid", json.getString("downreqid"));
		}
		if(!StringUtils.isBlank(json.getString("phoneNum"))){
			parameters.put(":phoneNum", json.getString("phoneNum"));
		}
		if(!StringUtils.isBlank(json.getString("downorderuuid"))){
			parameters.put(":downorderuuid", json.getString("downorderuuid"));
		}
		if(!StringUtils.isBlank(json.getString("status"))){
			parameters.put(":status", json.getString("status"));
		}
		if(!StringUtils.isBlank(json.getString("callstatus"))){
			parameters.put(":callstatus", json.getString("callstatus"));
		}
		if(!StringUtils.isBlank(json.getString("downfacevalue"))){
			parameters.put(":downfacevalue", json.getString("downfacevalue"));
		}
		if(json.containsKey("minute") && !StringUtils.isBlank(json.getString("minute"))){
			parameters.put(":minute", json.getString("minute"));
		}
		return parameters;
	}

	@Path("statusCallBack")
	@POST
	public String statusCallBack(String data, @Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "downorderuuid");
		if(result == null && checkRole(request, data)){
			JSONObject json = JsonUtils.converToJson(data);

			DownRechargeFlow flow = this.flowService.findById(json.getString("downorderuuid"));
			if(flow != null && (flow.getStatus() == 3 || flow.getStatus() == 2)){
				logger.info("statusCallBack:"+flow.getDowonphonenum());
				orderProcessing.sendResultDownShop(flow,true);
				logger.info("statusCallBack订单号:".concat(flow.getDownorderuuid()));
				return ResultMessage.getSucceed(null);
			}
			return ResultMessage.getFailt("");
		}
		return result;
	}

	@Autowired
	OrderThread orderThread;

	@Path("repeatFlowOrder")
	@POST
	public String repeatFlowOrder(String data, @Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "downorderuuid");
		if(result == null && checkRole(request, data)){
			JSONObject json = JsonUtils.converToJson(data);

			DownRechargeFlow flow = this.flowService.findById(json.getString("downorderuuid"));
			if(flow != null && (flow.getStatus() == Config.status[9] || flow.getStatus() == Config.status[11])){
				logger.info("repeatFlowOrder:"+flow.getDowonphonenum());
				flow.setStatus(Config.status[5]);
				flow.setRemark("重提订单");
				this.flowService.updateDownrechargeflow(flow);
				RechargeRest.orderQueue.add(flow);

				return ResultMessage.getSucceed(null);
			}
			return ResultMessage.getFailt("订单状态为人工的才能重提");
		}
		return result;
	}



	@Path("failtOrder")
	@POST
	public String failtOrder(String data, @Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "downorderuuid");
		if(result == null && checkRole(request, data)){
			JSONObject json = JsonUtils.converToJson(data);
			DownRechargeFlow flow = this.flowService.findById(json.getString("downorderuuid"));
			try{
				return orderFailt(flow,this.getUser(request,userService),"");
			}catch (Exception e){
				logger.info("failtOrderList:"+e.getMessage());
				return ResultMessage.getFailt("");
			}
		}
		return result;
	}

	private boolean checkRole(HttpServletRequest request,String data){
		String token = request.getHeader("token");
		if (token != null) {
			DecodedJWT jwt;
			try {
				jwt = JWT.decode(token);
				if (jwt != null) {
					JSONObject jsonJwt = JsonUtils.converToJson(jwt.getSubject());
					if (jsonJwt != null) {
						User login = userService.findByUserid(jsonJwt.getString(Config.tokenSignAttr));
						if(login != null ){
							return UserUtil.checkRole(login);
						}
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return false;
	}



	@Path("failtOrderList")
	@POST
	public String failtOrderList(String data, @Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "downorderuuids");
		if(result == null && checkRole(request, data)){
			JSONArray jsons = JsonUtils.converToJson(data).getJSONArray("downorderuuids");
			List<DownRechargeFlow> downRechargeFlows = new ArrayList<>();
			for(int i = 0 ; i < jsons.size(); i++){
				DownRechargeFlow flow = this.flowService.findById(jsons.getJSONObject(i).getString("downorderuuid"));
				if( flow != null && flow.getStatus() == Config.status[1]){
					downRechargeFlows.add(flow);
				}
			}
			if(downRechargeFlows.size() > 1){
				return ResultMessage.getFailt("成功的订单不能批量失败");
			}
			try{
				for(int i = 0 ; i < jsons.size(); i++){
					DownRechargeFlow flow = this.flowService.findById(jsons.getJSONObject(i).getString("downorderuuid"));
					orderFailt(flow,this.getUser(request,userService),"");
				}
				return ResultMessage.getSucceed(null);
			}catch (Exception e){
				logger.info("failtOrderList:"+e.getMessage());
				return ResultMessage.getFailt("");
			}
		}
		return result;
	}

	public String orderFailt(DownRechargeFlow flow,User user,String msg){
		if(flow != null){
			logger.info("failtOrderList:"+flow.getDowonphonenum());
			UpOrder order = this.orderService.findByIdFailUpOrder(flow.getDownorderuuid());
			if(order != null  && (order.getStatus() == Config.status[0] || order.getStatus() == Config.status[10]
					|| order.getStatus() == Config.status[11] || order.getStatus() == Config.status[1]
					|| order.getStatus() == Config.status[5])){

				order.setStatusremark(Config.orderStatus[2]);
				this.orderService.updateOrder(order);
				order.setRemark("人工操作失败");
				RechargeRest.failtUpOrder.add(order);
				if(user != null){
					logger.info("手动充值失败的订单号_failtOrderList:".concat(flow.getDownorderuuid())+":"+order.getUpphonenum()+":"+user.getUsername());
				}
				//flowService.orderRefund(order, upOrderService, flowService, shopService, taskExecutor, Config.orderMuError);
				return ResultMessage.getSucceed(null);
			}else if(order == null){
				try{
					logger.info("手动充值失败的订单:"+flow.getDowonphonenum());
					int tempStatus = flow.getStatus();
					flow.setStatus(Config.status[2]);
					flow.setStatusremark(StringUtils.isBlank(msg) ? "人工失败" : msg);
					Date end = DateUtils.getNowDate();
					flow.setDownendtime(end);
					flow.setRemark(Config.orderMuError);
					flow.setDownendtimesec(((Long)( end.getTime() - flow.getCreatetime().getTime())).intValue());

					DownShopInfo shop = shopService.findShopInfoByUuid(flow.getUserFlow().getUseruuid());
					if(shop != null){
						//下游订单失败 //0等待回调中 1 回调成功 2 失败 3 下游也在使用此值  4 订单发送到上游失败  5发送订单到上游成功
						flowService.updateCanelOrder(flow,shop,tempStatus,user);
						orderProcessing.sendResultDownShop(flow,true);
					}
					return ResultMessage.getSucceed(null);
				}catch (Exception e){
					e.printStackTrace();
					logger.info("orderFailt:"+e.getMessage());
				}
				return ResultMessage.getFailt("稍后再试,异常");
			}
			return ResultMessage.getFailt("稍后再试,异常");
		}else{
			return ResultMessage.getFailt("订单不存在");
		}
	}


	@Path("successOrder")
	@POST
	public String successOrder(String data, @Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "downorderuuid");
		if(result == null && checkRole(request, data)){
			JSONObject json = JsonUtils.converToJson(data);

			DownRechargeFlow flow = this.flowService.findById(json.getString("downorderuuid"));
			try {
				return this.successOrder(flow,this.getUser(request,userService),"");
			} catch (Exception e){
				logger.info("successOrderList:"+e.getMessage());
				return ResultMessage.getFailt("");
			}
		}
		return result;
	}

	@Path("successOrderList")
	@POST
	public String successOrderList(String data, @Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "downorderuuids");
		if(result == null && checkRole(request, data)){
			try {
				JSONArray jsons = JsonUtils.converToJson(data).getJSONArray("downorderuuids");
				for(int i = 0 ; i < jsons.size(); i++){
					DownRechargeFlow flow = this.flowService.findById(jsons.getJSONObject(i).getString("downorderuuid"));
					successOrder(flow,this.getUser(request,userService),"");
				}
			} catch (Exception e){
				logger.info("successOrderList:"+e.getMessage());
				return ResultMessage.getFailt("");
			}
			return ResultMessage.getSucceed(null);
		}
		return result;
	}

	/**
	 * msg 不为空 是task备注
	 * @param flow
	 * @param user
	 * @param msg
	 * @return
	 */
	public String successOrder(DownRechargeFlow flow,User user,String msg){
		if(flow != null){
			logger.info("successOrderList:"+flow.getDowonphonenum());
			UpOrder order = this.orderService.findByDownFlowId(flow.getDownorderuuid());
			//上游订单不为空时执行
			if(order != null && (order.getStatus() == Config.status[0] || order.getStatus() == Config.status[10] || order.getStatus() == Config.status[11])){
				order.setRemark("人工操作成功");
				RechargeRest.successUpOrder.add(order);
				if(user != null){
					logger.info("人工操作成功:".concat(flow.getDownorderuuid())+":"+order.getUpphonenum()+":"+user.getUsername());
				}
				return ResultMessage.getSucceed(null);
			}else{
				flow.setStatus(Config.status[1]);
				flow.setStatusremark(Config.orderSuccess);
				flow.setRemark(StringUtils.isBlank(msg) ? "人工操作成功" : msg);
				flow.setDownendtime(DateUtils.getNowDate());
				flowService.updateDownrechargeflow(flow);
				if(user != null){
					//添加日志
					DownOrderLog log = new DownOrderLog();
					log.setDownoperationtype(Config.orderMuSuccess);
					log.setDownordertype(Config.orderType[1]);
					log.setDownRechargeFlow(flow);
					log.setRemark(Config.orderMuSuccess);
					log.setUserLog(user);
					logDownService.addDownorderlog(log);
				}
				orderProcessing.sendResultDownShop(flow,true);
				return ResultMessage.getSucceed(null);
			}
		}else{
			return ResultMessage.getFailt("订单不存在:");
		}
	}

	/**
	 * {"useruuid":"402880ec60dbc14e0160dbc5e6b20007","busuuid":"66e91602-a142-11e7-9887-fcaa1456507e","provinceuuid":"e12e9650-9f98-11e7-9dc0-fcaa1456507e",
	 * "facevalue":"4","starttime":"2018-01-11","endtime":"2018-01-09"}
	 * @param data
	 * @param request
	 * @return
	 */
	@Path("getDownCount")
	@POST
	public String getDownCount(String data,@Context HttpServletRequest request){
		if(!StringUtils.isBlank(data)){
			String result = this.validationParameter(data, request, userService, "start","pageSize","useruuid","busuuid","provinceuuid","endtime","starttime","facevalue");
			if(result == null){
				JSONObject json = JsonUtils.getJSONOBJCT().fromObject(data);
				Map<String, Object> parameter = MapUtil.getMap();
				if(!StringUtils.isBlank(json.getString("useruuid")) && !json.getString("useruuid").equals("0")){
					parameter.put("useruuid", json.getString("useruuid"));
				}
				if(!StringUtils.isBlank(json.getString("busuuid")) && !json.getString("busuuid").equals("0")){
					parameter.put("busuuid", json.getString("busuuid"));
				}
				if(!StringUtils.isBlank(json.getString("provinceuuid")) && !json.getString("provinceuuid").equals("0")){
					parameter.put("provinceuuid", json.getString("provinceuuid"));
				}
				if(!StringUtils.isBlank(json.getString("facevalue")) && !json.getString("facevalue").equals("0")){
					parameter.put("facevalue", json.getString("facevalue"));
				}
				if(!StringUtils.isBlank(json.getString("endtime"))){
					parameter.put("endtime", json.getString("endtime"));
				}
				if(!StringUtils.isBlank(json.getString("starttime"))){
					parameter.put("starttime", json.getString("starttime"));
				}
				return ResultMessage.getSucceed( this.flowService.getDownCount(parameter,json.getInt("start"),json.getInt("pageSize")));
			}
			return result;
		}
		return ResultMessage.getSucceed(null);
	}

	@SuppressWarnings("static-access")
	@Path("exportdataDown")
	@POST
	public String exportdataDown(String data,@Context HttpServletRequest request){
		if(!StringUtils.isBlank(data)){
			String result = this.validationParameter(data, request, userService,"useruuid","busuuid","provinceuuid","endtime","starttime","facevalue");
			if(result == null){

				String token = request.getHeader("token");
				if (token != null) {
					DecodedJWT jwt;
					try {
						jwt = JWT.decode(token);
						if (jwt != null) {
							JSONObject jsonToken = JsonUtils.converToJson(jwt.getSubject());
							if (jsonToken != null) {
								JSONObject json = JsonUtils.getJSONOBJCT().fromObject(data);
								Map<String, Object> parameter = MapUtil.getMap();
								User login = userService.findByUserid(jsonToken.getString(Config.tokenSignAttr));
								if(login != null) {
									//检查是
									if (UserUtil.checkRoleDown(login)) {
										parameter.put("useruuid", login.getUseruuid());
										//检查日期不能大于一个月
										if(StringUtils.isBlank(json.getString("starttime"))){
											return ResultMessage.getFailt("开始日期必填");
										}
										//检查日期不能大于一个月
										if(StringUtils.isBlank(json.getString("endtime"))){
											return ResultMessage.getFailt("结束日期必填");
										}

										if(!DateUtils.parseYearDay(json.getString("starttime")).equals(DateUtils.parseYearDay(json.getString("endtime")))){
											return ResultMessage.getFailt("日期不能跨月");
										}
									}
								}

								if(!StringUtils.isBlank(json.getString("useruuid")) && !json.getString("useruuid").equals("0")){
									parameter.put("useruuid", json.getString("useruuid"));
								}
								if(!StringUtils.isBlank(json.getString("busuuid")) && !json.getString("busuuid").equals("0")){
									parameter.put("busuuid", json.getString("busuuid"));
								}
								if(!StringUtils.isBlank(json.getString("provinceuuid")) && !json.getString("provinceuuid").equals("0")){
									parameter.put("provinceuuid", json.getString("provinceuuid"));
								}
								if(!StringUtils.isBlank(json.getString("facevalue")) && !json.getString("facevalue").equals("0")){
									parameter.put("facevalue", json.getString("facevalue"));
								}
								if(!StringUtils.isBlank(json.getString("endtime"))){
									parameter.put("endtime", json.getString("endtime"));
								}
								if(!StringUtils.isBlank(json.getString("starttime"))){
									parameter.put("starttime", json.getString("starttime"));
								}
								JSONObject obj = JsonUtils.getJSONOBJCT();
								String exportResult = ExportExcelUtil.exportDown(this.flowService.exportDownCount(parameter));
								logger.info("exportResult:"+exportResult);
								if(exportResult != null){
									obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
									return ResultMessage.getSucceed(obj.toString());
								}else{
									return ResultMessage.getFailt("");
								}
							}
						}
					}catch (Exception e){
						e.printStackTrace();
					}
				}
			}
			return result;
		}
		return ResultMessage.getSucceed(null);
	}



	@SuppressWarnings("static-access")
	@Path("findUpFlowCount")
	@POST
	public String findUpFlowCount(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "useruuid","downprouuid","start","pageSize","starttime","endtime");
		if(result == null){
			JSONObject json = JSONObject.fromObject(data);

			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject jsonToken = JsonUtils.converToJson(jwt.getSubject());
						if (jsonToken != null) {
							User login = userService.findByUserid(jsonToken.getString(Config.tokenSignAttr));
							if(login != null) {
								//检查是
								if (UserUtil.checkRoleDown(login)) {
									json.put("useruuid",login.getUseruuid());

									//检查日期不能大于一个月
									if(StringUtils.isBlank(json.getString("starttime"))){
										return ResultMessage.getFailt("开始日期必填");
									}
									//检查日期不能大于一个月
									if(StringUtils.isBlank(json.getString("endtime"))){
										return ResultMessage.getFailt("结束日期必填");
									}

									if(!DateUtils.parseYearDay(json.getString("starttime")).equals(DateUtils.parseYearDay(json.getString("endtime")))){
										return ResultMessage.getFailt("日期不能跨月");
									}

								}
							}
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}
			}
			return ResultMessage.getSucceed(flowService.findDownFlowCount(json,json.getInt("start"),json.getInt("pageSize")));
		}
		return result;
	}

	/**
	 * 查询下游渠道订单数量 成功数量 失败数量
	 * @param data
	 * @param request
	 * @return
	 */
	@Path("findDownOrderCount")
	@POST
	public String findDownOrderCount(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole(request, userService);
		if(result == null){
			JSONObject json = JSONObject.fromObject(data);
			return ResultMessage.getSucceed(flowService.findDownOrderCount(json,json.getInt("start"),json.getInt("pageSize")));
		}
		return result;
	}

	@SuppressWarnings("static-access")
	@Path("exportDataDown")
	@POST
	public String exportDataDown(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "useruuid","downprouuid","start","pageSize","starttime","endtime");
		if(result == null){
			JSONObject json = JSONObject.fromObject(data);
			JSONObject obj = JsonUtils.getJSONOBJCT();

			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject jsonToken = JsonUtils.converToJson(jwt.getSubject());
						if (jsonToken != null) {
							User login = userService.findByUserid(jsonToken.getString(Config.tokenSignAttr));
							if(login != null) {
								//检查是
								if (UserUtil.checkRoleDown(login)) {
									json.put("useruuid",login.getUseruuid());

									//检查日期不能大于一个月
									if(StringUtils.isBlank(json.getString("starttime"))){
										return ResultMessage.getFailt("开始日期必填");
									}
									//检查日期不能大于一个月
									if(StringUtils.isBlank(json.getString("endtime"))){
										return ResultMessage.getFailt("结束日期必填");
									}

									if(!DateUtils.parseYearDay(json.getString("starttime")).equals(DateUtils.parseYearDay(json.getString("endtime")))){
										return ResultMessage.getFailt("日期不能跨月");
									}

								}
							}
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}
			}

			String exportResult = ExportExcelUtil.exportDownFlowJSON(this.flowService.exportDataDown(json));
			logger.info("exportResult:"+exportResult);
			if(exportResult != null){
				obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
				return ResultMessage.getSucceed(obj.toString());
			}else{
				return ResultMessage.getFailt("");
			}
		}
		return result;
	}

	@Path("restTest")
	@POST
	public String restTest(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole( request, userService);
		if(result == null){
			//return rest.recharge(data, request);
		}
		return ResultMessage.getFailt("");
	}

	@Autowired
	IMobileService mobileService;

	@Autowired
	IDownShopProductService productService;

	@Autowired
	IDownShopInfoService downShopService;

	@Autowired
	protected RechargeRest rechargeRest;


	@Path("restBatch")
	@POST
	public String restBatch(String data,@Context HttpServletRequest request){
		String result = this.validationParameterGetRole( request, userService);
		//失败的号码
		String phone = "";
		String token = request.getHeader("token");
		if (token != null) {
			DecodedJWT jwt;
			try {
				jwt = JWT.decode(token);
				if (jwt != null) {
					JSONObject json = JsonUtils.converToJson(jwt.getSubject());
					if (json != null) {
						User login = userService.findByUserid(json.getString(Config.tokenSignAttr));
						if (login != null && UserUtil.checkRoleAll(login)) {
							logger.info("restBatch:"+data+":user:"+login.getUsername());
							if(result == null){
								com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(data);

								com.alibaba.fastjson.JSONArray arrays = jsonObject.getJSONArray("orders");
								DownShopInfo downShopInfo = this.downShopService.findShopInfoByUuid(arrays.getJSONObject(0).getString("uid"));
								if(downShopInfo == null){
									return ResultMessage.getFailt("分销商不存在");
								}
								for(int i = 0 ; i < arrays.size(); i++){
									//计算签名 md5
									com.alibaba.fastjson.JSONObject rech = arrays.getJSONObject(i);
									//查询产品id 按分销商 号码地市
//									Mobile mobile = mobileService.findPhone(rech.getString("phone").substring(0, 7));
//									if (mobile == null) {
//										mobile = rechargeRest.checkMobile(rech.getString("phone"));
//										if(mobile == null){
//											logger.info("restBatch_error号码地市不存在,请添加:"+ rech);
//											//return ResultMessage.getFailt("号码地市不存在,请添加:" + rech.getString("phone"));
//											break;
//										}
//									}
//									if(mobile != null){
										AutoOrderService.manualOrder.add((ManualRechargeOrder) JSONObject.toBean(JSONObject.fromObject(rech), ManualRechargeOrder.class));
//									}else{
										//失败订单
//										phone +=" " +rech.getString("phone");
//										createFailt((ManualRechargeOrder) JSONObject.toBean(JSONObject.fromObject(rech), ManualRechargeOrder.class),"不支持的号码");
//									}
								}
								//保存本次充值订单金额
								ManualOrder manualOrder = new ManualOrder();

								manualOrder.setManualUser(new User(jsonObject.getString("useruuid")));
								manualOrder.setCreatedTime(DateUtils.getNowDate());
								manualOrder.setOrderNum(Integer.parseInt(jsonObject.getString("orderNum")));
								manualOrder.setOrderMoney(new BigDecimal(jsonObject.getString("orderMoney")));
								iManualOrderService.saveManualOrder(manualOrder);

								return ResultMessage.getSucceed(null);
							}
						}
					}
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 创建失败订单
	 * @param manualRechargeOrder
	 */
	public void createFailt(ManualRechargeOrder manualRechargeOrder,String msg){
		final DownRechargeFlow flow = new DownRechargeFlow();
		Date date = DateUtils.getNowDate();
		flow.setCreatetime(date);

		flow.setDownreqid(manualRechargeOrder.getOrderId());
		flow.setUserFlow(new User(manualRechargeOrder.getUid()));
		flow.setRechargeamount(new BigDecimal(manualRechargeOrder.getMoney()));
		flow.setDowonphonenum(manualRechargeOrder.getPhone());
		flow.setOperators(null);
		flow.setDownnotificationaddress(manualRechargeOrder.getNotify());
		flow.setStatus(Config.status[2]);
		flow.setBusCode("");
		flow.setProvince("");
		flow.setCityName("");
		flow.setCallStatus(Config.callStatus[1]);
		flow.setDownendtimesec(Config.status[3]);
		flow.setDownShopProduct(null);
		flow.setDiscount(BigDecimal.ZERO);
		flow.setDiscountAmount(BigDecimal.ZERO);
		flow.setRemark(msg == null ? "" : msg);
		//重复提交次数 产品默认为1
		flow.setDownreqnum(1);
		flow.setStatusremark("");
		flowService.addDownrechargeflow(flow,null);
	}

	/**
	 * 查询用户按天统计手工充值金额和笔数
	 * @param data
	 * @param request
	 * @return
	 */
	@Path("findUserManualOrder")
	@POST
	public String findUserManualOrder(String data,@Context HttpServletRequest request){
		String result = this.validationParameterToken( request, userService);
		String token = request.getHeader("token");
		if (token != null) {
			DecodedJWT jwt;
			try {
				jwt = JWT.decode(token);
				if (jwt != null) {
					JSONObject json = JsonUtils.converToJson(jwt.getSubject());
					if (json != null) {
						User login = userService.findByUserid(json.getString(Config.tokenSignAttr));
						if (login != null && UserUtil.checkRoleAll(login)) {

							ManualOrder manualOrder = this.iManualOrderService.findByUserId(JSONObject.fromObject(data).getString("useruuid"),DateUtils.toShortDate(DateUtils.getNowDate()));
							if(manualOrder != null){
								return ResultMessage.getSucceed( com.alibaba.fastjson.JSONObject.toJSONString(manualOrder));
							}else{
								//当日没有提交
								return ResultMessage.getSucceed( "");
							}
						}
					}
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return result;
	}


	@Path("failtUpOrder")
	@POST
	public String failtUpOrder(String data, @Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "upOrders");
		if(result == null && checkRole(request, data)){
			JSONArray jsons = JsonUtils.converToJson(data).getJSONArray("upOrders");
			List<DownRechargeFlow> downRechargeFlows = new ArrayList<>();
			for(int i = 0 ; i < jsons.size(); i++){
				UpOrder upOrder = this.upOrderService.findByCallId(jsons.getJSONObject(i).getString("upOrderId"));
				if( upOrder != null && upOrder.getStatus() == Config.status[1]){
					downRechargeFlows.add(upOrder.getDownRechargeFlow());
				}
			}
			if(downRechargeFlows.size() > 1){
				return ResultMessage.getFailt("成功的订单不能批量失败");
			}
			for(int i = 0 ; i < jsons.size(); i++){
				UpOrder upOrder = this.upOrderService.findByCallId(jsons.getJSONObject(i).getString("upOrderId"));
				if(upOrder != null ){
					orderFailt(upOrder.getDownRechargeFlow(),this.getUser(request,userService),"");
				}

			}
			return ResultMessage.getSucceed(null);
		}
		return result;
	}

	@Path("successUpOrder")
	@POST
	public String successUpOrder(String data, @Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "upOrders");
		if(result == null && checkRole(request, data)){
			JSONArray jsons = JsonUtils.converToJson(data).getJSONArray("upOrders");
			for(int i = 0 ; i < jsons.size(); i++){
				UpOrder upOrder = this.upOrderService.findByCallId(jsons.getJSONObject(i).getString("upOrderId"));
				if(upOrder != null){
					successOrder(upOrder.getDownRechargeFlow(),this.getUser(request,userService),"");
				}
			}
			return ResultMessage.getSucceed(null);
		}
		return result;
	}
}
